package com.travel.server.manager.impl.datasource;

import com.travel.server.manager.impl.datasource.util.DruidUtil;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;

import javax.sql.DataSource;
import java.sql.SQLException;

/**
 * @Author: LiZhenhui
 * @Date: 2018/10/16 14:51
 * @Desc:
 */
@Configuration
@MapperScan(basePackages = "com.travel.server.manager.dao", sqlSessionFactoryRef = MybatisConfig.SQL_SESSION_FACTORY_NAME)
public class MybatisConfig {

    @Value("${druid.mysql.driver}")
    public String driver;

    @Value("${druid.mysql.url}")
    public String url;

    @Value("${druid.mysql.username}")
    public String username;

    @Value("${druid.mysql.password}")
    public String password;

    @Value("${druid.mysql.initial.size}")
    public int initialSize;

    @Value("${druid.mysql.min.idle}")
    public int minIdle;

    @Value("${druid.mysql.max.active}")
    public int maxActive;

    @Value("${druid.mysql.max.wait}")
    public int maxWait;

    public static final String DATASOURCE_NAME = "MANAGER_DATASOURCE";

    public static final String SQL_SESSION_FACTORY_NAME = "MANAGER_DATASOURCE_SESSION_FACTORY_NAME";

    public static final String UNIQUE_RESOURCE_NAME = "MANAGER_DB";

    @Autowired
    @Qualifier(value = DATASOURCE_NAME)
    DataSource dataSource;

    @Bean(name = SQL_SESSION_FACTORY_NAME)
    public SqlSessionFactory createSqlSessionFactoryBean() throws Exception {
        SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
        sqlSessionFactoryBean.setDataSource(dataSource);
        sqlSessionFactoryBean.setMapperLocations(new PathMatchingResourcePatternResolver()
                .getResources("sql-map/*.xml"));
        return sqlSessionFactoryBean.getObject();
    }

    @Bean(name = DATASOURCE_NAME)
    public DataSource druidDataSource() throws SQLException {
        return DruidUtil.createXADataSource(driver,UNIQUE_RESOURCE_NAME, url, username, password, initialSize, minIdle, maxActive, maxWait);
    }
}
